package com.feicheng.iou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.iou.bean.InformationBean;
import com.feicheng.iou.commom.ReturnCode;
import com.feicheng.iou.constant.ProvideConstant;
import com.feicheng.iou.constant.SessionConstant;
import com.feicheng.iou.constant.StatuConstant;
import com.feicheng.iou.constant.StatusCodeConstant;
import com.feicheng.iou.entity.*;
import com.feicheng.iou.exception.SystemException;
import com.feicheng.iou.exception.SystemExceptionV110;
import com.feicheng.iou.mapper.*;
import com.feicheng.iou.pojo.BaomingPOJO;
import com.feicheng.iou.pojo.ResultBaomingPOJO;
import com.feicheng.iou.pojo.login.LoginReturnPOJO;
import com.feicheng.iou.pojo.login.PermissionLevelTwoPOJO;
import com.feicheng.iou.pojo.login.PermissionListPOJO;
import com.feicheng.iou.result.ResultInfo;
import com.feicheng.iou.result.ResultInfoV110;
import com.feicheng.iou.service.BaomingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feicheng.iou.util.PageUtil;
import lombok.Setter;
import com.feicheng.iou.entity.Baoming;
import com.feicheng.iou.mapper.BaomingMapper;
import com.feicheng.iou.pojo.lifeCyclePOJO.BaomingAndBackviewPOJO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianchunlei
 * @since 2021-06-28
 */
@Service
@Slf4j
@Setter
public class BaomingServiceImpl extends ServiceImpl<BaomingMapper, Baoming> implements BaomingService {
    @Autowired
    private BaomingMapper baomingMapper;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private PaymentItemMapper paymentItemMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RelMapper relMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ResourceRecordMapper resourceRecordMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private ProjectServiceMapper projectServiceMapper;
    @Autowired
    private PaymentOptionsMapper paymentOptionsMapper;


    @Override
    public ResultInfoV110 delete() {
        return null;
    }

    @Override
    public ResultInfoV110 selectAgainShow(Integer studentId) {
        QueryWrapper<Baoming> baomingQueryWrapper = new QueryWrapper<>();
        baomingQueryWrapper.eq("student_id",studentId);
        Baoming baoming = baomingMapper.selectOne(baomingQueryWrapper);
        QueryWrapper<Rel> relQueryWrapper = new QueryWrapper<>();
        relQueryWrapper.eq("student_id",studentId);
        Rel rel = relMapper.selectOne(relQueryWrapper);
        Integer userId = rel.getUserId();
        Integer paymentId = rel.getPaymentId();
        User user = userMapper.selectById(userId);
        Payment payment = paymentMapper.selectById(paymentId);
        QueryWrapper<PaymentItem> paymentItemQueryWrapper = new QueryWrapper<>();
        paymentItemQueryWrapper.eq("p_id",paymentId);
        List<PaymentItem> paymentItems = paymentItemMapper.selectList(paymentItemQueryWrapper);
//        ArrayList paymentItemIds = new ArrayList<>();
//        for (PaymentItem paymentItem:paymentItems){
//            Integer paymentItemId = paymentItem.getId();
//            paymentItemIds.add(paymentItemId);
//        }
        HashMap<String, Object> resultMap = new HashMap<>();
        ProjectService projectService = projectServiceMapper.selectById(rel.getServiceId());
        PaymentOptions paymentOptions = paymentOptionsMapper.selectById(payment.getPoid());
        resultMap.put("baoming",baoming);
        resultMap.put("rel",rel);
        resultMap.put("user",user);
        resultMap.put("payment",payment);
        resultMap.put("paymentItems",paymentItems);
        resultMap.put("projectService",projectService);
        resultMap.put("paymentOptions",paymentOptions);
        return ResultInfoV110.success(resultMap);
    }

    @Override
    public ResultInfoV110 againInsert(BaomingPOJO baomingPOJO, HttpServletRequest request) {
        log.info("BaomingServiceImpl 的againInsert方法进入");
        Integer studentId = baomingPOJO.getBaoming().getStudentId();
        QueryWrapper<Baoming> baomingQueryWrapper = new QueryWrapper<>();
        baomingQueryWrapper.eq("student_id",studentId);
        baomingMapper.delete(baomingQueryWrapper);
        QueryWrapper<Rel> relQueryWrapper = new QueryWrapper<>();
        relQueryWrapper.eq("student_id",studentId);
        Rel rel = relMapper.selectOne(relQueryWrapper);
        Integer userId = rel.getUserId();
        Integer paymentId = rel.getPaymentId();
        userMapper.deleteById(userId);
        paymentMapper.deleteById(paymentId);
        QueryWrapper<PaymentItem> paymentItemQueryWrapper = new QueryWrapper<>();
        paymentItemQueryWrapper.eq("p_id",paymentId);
        paymentItemMapper.delete(paymentItemQueryWrapper);
        QueryWrapper<Rel> relDeleteQueryWrapper = new QueryWrapper<>();
        relQueryWrapper.eq("student_id",studentId).eq("payment_id",paymentId);
        relMapper.delete(relQueryWrapper);

        this.insert(baomingPOJO,request);
        return ResultInfoV110.success();
    }

    /**
     * @param baomingPOJO
     * @return ResultInfoV110
     * @Author luoxin
     * @Description TODO
     * @Date 10:47 上午 2021/8/9
     */
    @Override
    @Transactional
    public ResultInfoV110 insert(BaomingPOJO baomingPOJO, HttpServletRequest request) {
        log.info("BaomingServiceImpl 的insert方法进入");

        //取到当前登录用户session中的userid
        LoginReturnPOJO attribute = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        Integer userId = attribute.getUser().getUserId();

        /* 解析BaomingPOJO */
        Baoming baoming = baomingPOJO.getBaoming();
//        PaymentItem paymentItem = baomingPOJO.getPaymentItem();
        Payment payment = baomingPOJO.getPayment();
        User user = baomingPOJO.getUser();
        ProjectService projectService = baomingPOJO.getProjectService();
        PaymentItem paymentItem = new PaymentItem();
        PaymentOptions paymentOptions = baomingPOJO.getPaymentOptions();
        Integer studentId = baoming.getStudentId();
        QueryWrapper<Resource> wrapper = new QueryWrapper<>();
        wrapper.eq("student_id", studentId);
        Resource resource = resourceMapper.selectOne(wrapper);

        //处理报名信息的添加
        baoming.setCu(userId);
        baoming.setUu(userId);
        int insertBaomingResult = baomingMapper.insert(baoming);
        if (insertBaomingResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "添加报名信息"));
        }
        //修改resource的Statu为待回访
        resource.setUu(userId);
        resource.setStatu(StatuConstant.YIBAOMING);
        //根据获取resource的ID修改推进状态
        int updateResourceResult = resourceMapper.updateById(resource);
        //验证验证是否成功修改线索推进状态
        if (updateResourceResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "修改线索信息"));
        }


        //取得课程的总费用
        BigDecimal amount = projectService.getAmount();
        //取得月服务费率
        BigDecimal rate = paymentOptions.getRate();

        BigDecimal bigDecimal = new BigDecimal(100);
        BigDecimal monthRate = rate.divide(bigDecimal, 6, BigDecimal.ROUND_UNNECESSARY);
        //月服务管理费用= 课程总费用 * 月服务费率
        BigDecimal Service = amount.multiply(monthRate);

        //取得paymentOptions表中的利息期数和本金期数
        Integer base = paymentOptions.getBase();
        Integer main = paymentOptions.getMain();
        //总期数为利息期数和本金期数
        Integer number = base + main;
        //总服务管理费用= 月服务管理费用 * 总月数
        BigDecimal bigDecimalNumber = new BigDecimal(number);
        BigDecimal totalService = Service.multiply(bigDecimalNumber);
        //总金额 = 总服务管理费用 + 课程的总费用
        BigDecimal totalAmount = totalService.add(amount);

        payment.setTotalAmount(totalAmount);
        payment.setNumber(number.toString());
        //添加支付信息，默认状态为申请中
        payment.setStatus(ProvideConstant.DAIQUEREN);
        payment.setCu(userId);
        payment.setUu(userId);
        int insertPaymentResult = paymentMapper.insert(payment);
        if (insertPaymentResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "添加支付信息"));
        }


        //判断分期是否为零期
        if (number == 0) {

//            paymentItem.setReceivables(amount);
//            paymentItem.setPayable(new BigDecimal(0));
//            paymentItem.setPid(payment.getId());
//            paymentItem.setService(new BigDecimal(0));
//            paymentItem.setNumber(0);
//            paymentItem.setStatus("--");
////            paymentItem.setPayMethod("微信支付");
//            paymentItem.setCu(userId);
//            paymentItem.setUu(userId);
//            int insertPaymentItemResult = paymentItemMapper.insert(paymentItem);
//            if (insertPaymentItemResult == 0) {
//                throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "添加分期列表"));
//            }
        } else {
            //每月课程费
            BigDecimal bigDecimalMain = new BigDecimal(main);
            BigDecimal monthClassaMounnt = amount.divide(bigDecimalMain, 6, BigDecimal.ROUND_UP);
            //每月还款费用（不包括前期利息月）=每月服务费+每月课程费
            BigDecimal monthReceivables = Service.add(monthClassaMounnt);
            //循环处理还款记录添加
            for (int i = 0; i < number; i++) {
//                LocalDate requestDate = payment.getRequestDate();
//                LocalDate localDate = requestDate.withDayOfMonth(Integer.valueOf(paymentOptions.getPayDate())).plusMonths(i + 1);
//                LocalDateTime localDateTime = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toLocalDateTime();
//                paymentItem.setPlanPayDate(localDateTime);
                if (paymentOptions.getBase() >= i + 1) {
                    paymentItem.setReceivables(new BigDecimal(0));
                    paymentItem.setPayable(Service);
                } else {
                    paymentItem.setPayable(monthReceivables);
                    paymentItem.setReceivables(monthClassaMounnt);
                }
                paymentItem.setPid(payment.getId());
                paymentItem.setService(Service);
                paymentItem.setNumber(i + 1);
                paymentItem.setStatus("--");
//                paymentItem.setPayMethod("微信支付");
                paymentItem.setCu(userId);
                paymentItem.setUu(userId);
                int insertPaymentItemResult = paymentItemMapper.insert(paymentItem);
                if (insertPaymentItemResult == 0) {
                    throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "添加分期列表"));
                }
            }
        }
        //处理用户信息的添加
        user.setCu(userId);
        user.setUu(userId);
        int insertUserResult = userMapper.insert(user);
        if (insertUserResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "添加用户"));
        }

        //创建新的rel对象，封装数据
        Rel rel = new Rel();
        rel.setServiceId(projectService.getId());
        rel.setStudentId(baoming.getStudentId());
        rel.setPaymentId(payment.getId());
        rel.setUserId(user.getUserId());
        //处理rel表信息的添加
        int insertRelResult = relMapper.insert(rel);
        if (insertRelResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "添加用户关联表"));
        }

        log.info("BaomingServiceImpl 的insert方法结束");
        return ResultInfoV110.success();
    }

    @Override
    public ResultInfoV110 selectBaominngList(BaomingPOJO baomingPOJO, HttpServletRequest request) {
        log.info("BaomingServiceImpl类seleclBaominngList进去，参数为" + baomingPOJO);

        //定义一个放返回数据的Map
        HashMap<Object, Object> resultMap = new HashMap<>();
        //获取传入数据中的pege当前页，size每页条数得出当前页起始数据索引
        Integer pageIndex = PageUtil.getPageIndex(baomingPOJO.getPage(), baomingPOJO.getSize());
        //把数据索引封装到tryPOJO
        baomingPOJO.setPageIndex(pageIndex);
        //调用Mapper中查询条数的方法得出条数封装进tryPOJO
        //检查是否拥有可分配权限，根据用户不同显示不同的数据
        LoginReturnPOJO loginReturnPOJO = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        List<PermissionListPOJO> permissions = loginReturnPOJO.getPermissions();

        //定一个boolean的变量校验权限是否为可分配
        boolean kefenpeiFlag = false;
        for (PermissionListPOJO permissionListPOJO : permissions) {
            List<PermissionLevelTwoPOJO> permissionsTwo = permissionListPOJO.getPermissions();
            for (PermissionLevelTwoPOJO permissionLevelTwoPOJO : permissionsTwo) {
                if (permissionLevelTwoPOJO.getName().equals("可分配")) {
                    kefenpeiFlag = true;
                    break;  //如何退出两层for需调研
                }
            }
        }

        if (baomingPOJO.getBaoming().getAutor() == null) {
            if (kefenpeiFlag) {
                baomingPOJO.getBaoming().setAutor(null);
            } else {
                baomingPOJO.getBaoming().setAutor(loginReturnPOJO.getUser().getUserId());
            }
        }

        baomingPOJO.setTotal(baomingMapper.queryBaomingAllCount(baomingPOJO));
        //根据传入的pojo查询，结果封装到resultTryPOJOSList
        List<ResultBaomingPOJO> resultBaomingPOJOList = baomingMapper.queryBaomingAll(baomingPOJO);
        //获取pageutil里的pageinfo里的数据封装到pageinfo这个map
        Map<String, Integer> pageInfo = PageUtil.getPageInfo(baomingPOJO.getPage(), baomingPOJO.getSize(), baomingPOJO.getTotal());

        //把pageinnfo这个map封装到resultMap中
        resultMap.put("pageInfo", pageInfo);
        //把resourcePOJOSList这个list封装到resultMap中
        resultMap.put("list", resultBaomingPOJOList);


        log.info("seleclBaominngList类listAll结束");
        return ResultInfoV110.success(resultMap);
    }

    @Override
    public ResultInfoV110 selectBaominginfo(Integer id) {
        log.info("seleclBaominngImpl类selectBaominginfo方法进入");

        //定义一个存放查询结果数据的Map
        Map<String, Object> resultMap = new HashMap<>();

        //查询报名信息
        Baoming baoming = baomingMapper.selectById(id);
        //从查询到的报名信息中取出studentID
        Integer studentId = baoming.getStudentId();
        /* 定义一个对比studentId的QueryWrapper，并根据此查询对应线索信息 */
        QueryWrapper<Resource> resourceQueryWrapper = new QueryWrapper<>();
        resourceQueryWrapper.eq("student_id", studentId);
        Resource resource = resourceMapper.selectOne(resourceQueryWrapper);

        /* 定义一个对比studentId的QueryWrapper，并根据此查询对应学生信息 */
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("id", studentId);
        Student student = studentMapper.selectOne(studentQueryWrapper);

        /* 定义一个对比resourceId的QueryWrapper，并根据此查询对应线索信息 */
        Integer resourceId = resource.getId();
        QueryWrapper<ResourceRecord> resourceRecordQueryWrapper = new QueryWrapper<>();
        resourceRecordQueryWrapper.eq("resource_id", resourceId);
        ResourceRecord resourceRecord = resourceRecordMapper.selectOne(resourceRecordQueryWrapper);

        /* 查询到的数据全部封装放入resultMap */
        resultMap.put("baoming", baoming);
        resultMap.put("resource", resource);
        resultMap.put("student", student);
        resultMap.put("resourceRecord", resourceRecord);

        log.info("seleclBaominngImpl类selectBaominginfo方法结束");
        return ResultInfoV110.success(resultMap);
    }

    @Override
    public ResultInfoV110 update(BaomingPOJO baomingPOJO) {
        log.info("seleclBaominngImpl类update方法进入");

        /* 解析baomingpojo中的信息 */
        Baoming baoming = baomingPOJO.getBaoming();//解析报名信息
        Student student = baomingPOJO.getStudent();//解析学生信息
        Resource resource = baomingPOJO.getResource();//解析线索信息
        ResourceRecord resourceRecord = baomingPOJO.getResourceRecord();//解析线索记录信息

        //调用mapper，修改学生信息
        int updateStudentByIdResult = studentMapper.updateById(student);
        //验证修改学生信息是否成功
        if (updateStudentByIdResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改学生信息"));
        }
        //调用mapper，修改报名信息
        int updateBaomingByIdResult = baomingMapper.updateById(baoming);
        //验证修改报名信息是否成功
        if (updateBaomingByIdResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改报名信息"));
        }
        //调用mapper，修改线索信息
        int updateResourceByIdResult = resourceMapper.updateById(resource);
        //验证修改线索信息是否成功
        if (updateResourceByIdResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改线录信息"));
        }
        //调用mapper，修改线索记录信息
        int updateResourceRecordByIdResult = resourceRecordMapper.updateById(resourceRecord);
        //验证修改线索记录信息是否成功
        if (updateResourceRecordByIdResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改线索记录信息"));
        }


        log.info("seleclBaominngImpl类update方法结束");

        return ResultInfoV110.success();
    }

    @Override
    public ResultInfoV110 updateAutor(Integer baomingId, Integer autorId) {
        log.info("seleclBaominngImpl类updateAutor方法进入");

        /* 把取得的数据放入对象 */
        Baoming baoming = new Baoming();
        baoming.setId(baomingId);
        baoming.setAutor(autorId);
        /* 调用mapper，修改线索跟进人 */
        int updateBaomingByIdResult = baomingMapper.updateById(baoming);
        if (updateBaomingByIdResult == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改报名信息"));
        }

        log.info("seleclBaominngImpl类updateAutor方法结束");
        return ResultInfoV110.success();
    }


    @Autowired
    private BaomingAndBackviewPOJO baomingAndBackviewPOJO;

    @Override
    public ResultInfo selectBaomingByStudentId(Integer studentId) {
        log.info("BaomingServiceImpl的selectBaomingByStudentId方法进入,参数studentId为"+studentId);

        //根据学生Id查看报名信息
        QueryWrapper<Baoming> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        Baoming baoming = baomingMapper.selectOne(queryWrapper);
        baomingAndBackviewPOJO.setBaoming(baoming);
        return ResultInfo.success(baoming);

    }
}
